<template>
  <div>
    <div class="search">
      <van-search
        class="left"
        v-model="value"
        placeholder="请输入搜索关键词"
        @search="search"
        @keyup="fil"
      />
      <button class="right" @click="search">搜索</button>

      <van-list class="list">
        <van-cell v-for="item in reslist" :key="item" :title="item" />
      </van-list>
    </div>

    <h5>历史记录 <van-icon @click="remove" name="cross" /></h5>
    <van-panel>
      <div v-for="(item, index) in history" :key="index" v-show="index < 9">
        {{ item }}
      </div>
    </van-panel>
  </div>
</template>
<script>
import { Dialog } from "vant";

export default {
  data() {
    return {
      list: [
        "北京北",
        "北京南",
        "北京西",
        "北京东",
        "昌平西",
        "昌平东关",
        "昌平难关",
      ],
      reslist: [],
      value: "",
      history: JSON.parse(localStorage.getItem("history")) || [],
      //如果本地存储中有就从本地存储中拿 如果没有 就为【】
    };
  },
  methods: {
    fil() {
      if (this.value != "") {
        this.reslist = this.list.filter((item) => {
          return item.includes(this.value);
        });
      } else {
        this.reslist = [];
      }
    },
    search() {    
      this.history.unshift(this.value);
      //在最前面添加 保证展示的是最新的三条历史记录

      localStorage.setItem("history", JSON.stringify(this.history));
      //每次历史记录更新 都会存在本地存储中
      console.log(this.value);
      this.$router.push({ path: "/list", query: { value: this.value } });
    },

    remove() {
      Dialog.confirm({
        title: "标题",
        message: "弹窗内容",
      })
        .then(() => {
          // on confirm
          this.history = [];
          localStorage.removeItem("history");
          //执行点击确认的操作 把本地存储中的history清除掉 把data里的history也清除掉
        })
        .catch(() => {
          // on cancel
        });
    },
  },
};
</script>
<style lang="scss">
.search {
  display: flex;
  align-items: center;
  position: relative;
  > .list {
    position: absolute;
    left: 0px;
    top: 50px;
    width: 100%;
    z-index: 10;
  }
  .left {
    flex: 5;
  }
  .right {
    flex: 1;
    height: 40px;
  }
}
</style>
